#include <highgui.h>
#include <iostream>


#include <stdlib.h>
#include <string.h>

bool prefixComp(int prefixLen, char* str1, char* str2) {
	for (int i=0; i<prefixLen; i++) {
		if (str1[i] == str2[i]) continue;
		return false;
	}
	return true;
}

int main( int argc, char** argv ) {
	cvNamedWindow( "Example Camera Display", CV_WINDOW_AUTOSIZE );
	
	int camNum = 0;
	
	bool lowres = false;
	
	char* lowresString = "--lowres";
	char* camString = "--cam=n";
	int camStringLen = strlen(camString);
	
	switch (argc) {
		case 3:
			if ( strcmp(argv[2],lowresString)==0 ) { //strcmp returns 0 for true!
				lowres = true;
			} else if ( strlen(argv[2]) == camStringLen && prefixComp(camStringLen-1,argv[2],camString) )  {
				camNum = atoi( &(argv[2][camStringLen]) );
			}
			//NOTE: No break!
		case 2:
			if ( strcmp(argv[1],lowresString)==0 ) { //strcmp returns 0 for true!
				lowres = true;
			} else if ( strlen(argv[1]) == camStringLen && prefixComp(camStringLen-1,argv[1],camString) )  {
				camNum = atoi( &(argv[1][camStringLen]) );
			}
			break;
		default:
			break;
	}
	
	CvCapture* capture = cvCaptureFromCAM(camNum);
	
	if (lowres) {
		cvSetCaptureProperty( capture, CV_CAP_PROP_FRAME_WIDTH, 640);
		cvSetCaptureProperty( capture, CV_CAP_PROP_FRAME_HEIGHT, 480);
	}
	
	IplImage* frame;
	while(1) {
		frame = cvQueryFrame( capture );
		if( !frame ) break;
		cvShowImage( "Example Camera Display", frame );
		char c = cvWaitKey(33);
		if( c == 27 ) break;
	}
	cvReleaseCapture( &capture );
	cvDestroyWindow( "Example Camera Display" );
}

